package com.chuangjiangx.member.score.ddd.application;

import com.chuangjiangx.commons.exception.BaseException;
import com.chuangjiangx.dddbase.application.Application;

import com.chuangjiangx.member.score.ddd.domain.model.MbrScoreGiftRule;
import com.chuangjiangx.member.score.ddd.domain.repository.MbrScoreGiftRuleRepository;
import com.chuangjiangx.member.score.ddd.application.command.CreateMbrScoreGiftRuleCommand;
import com.chuangjiangx.member.score.ddd.application.command.ModifyMbrScoreGiftRuleCommand;

import com.chuangjiangx.member.basic.ddd.domain.model.MbrScoreGiftRuleId;
import com.chuangjiangx.member.basic.ddd.domain.model.MerchantId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.Objects;

/**
 * 兑换规则操作类
 */
@Service
public class MbrScoreGiftRuleApplication implements Application {

    private final MbrScoreGiftRuleRepository mbrScoreGiftRuleRepository;

    private Logger logger = LoggerFactory.getLogger(MbrScoreGiftRuleApplication.class);

    @Autowired
    public MbrScoreGiftRuleApplication(
            MbrScoreGiftRuleRepository mbrScoreGiftRuleRepository) {
        this.mbrScoreGiftRuleRepository = mbrScoreGiftRuleRepository;
    }

    /**
     * 创建积分兑换规则--商户平台
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public void createMbrScoreGiftRule(CreateMbrScoreGiftRuleCommand command) throws Exception {

        // 兑换规则数量最大限制50个
        int count = mbrScoreGiftRuleRepository.countByMerchantId(new MerchantId(command.getMerchantId()));
        Assert.isTrue(count < 50, "积分兑换规则最多只能有50个");

        MbrScoreGiftRule mbrMbrScoreGiftRule = new MbrScoreGiftRule(
                new MerchantId(command.getMerchantId()),
                command.getScore(), command.getGoodsName(),
                command.getGoodsPrice(), command.getImageURL(),
                0L, command.getExchangeLimit(),
                command.getRemark(), command.getTotalGiftLimit(),
                command.getStartTime(),command.getEndTime()
        );
        mbrScoreGiftRuleRepository.save(mbrMbrScoreGiftRule);
    }

    /**
     * 修改积分兑换规则--商户平台
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public void modifyMbrScoreGiftRule(ModifyMbrScoreGiftRuleCommand command) throws Exception {

        logger.info("修改积分兑换规则参数:" + command);
        Assert.notNull(command.getMerchantId(), "商户id不能为空");

        MbrScoreGiftRule mbrMbrScoreGiftRule = mbrScoreGiftRuleRepository.fromId(new MbrScoreGiftRuleId(command.getId()));
        Assert.notNull(mbrMbrScoreGiftRule, "积分兑换规则不存在");
        Assert.isTrue(mbrMbrScoreGiftRule.getMerchantId().getId() == command.getMerchantId(),
                "规则不属于当前商户");

        if (new Date().after(mbrMbrScoreGiftRule.getStartTime())) {
            throw new BaseException("","活动已开始，无法修改");
        }
        mbrMbrScoreGiftRule.updateModifyScoreGift(
                command.getScore(), command.getGoodsName(), command.getGoodsPrice(), command.getImageURL(), command.getCount(),
                command.getExchangeLimit(),command.getRemark(),command.getTotalGiftLimit(),
                command.getStartTime(),command.getEndTime());
        mbrMbrScoreGiftRule.setId(new MbrScoreGiftRuleId(command.getId()));
        mbrScoreGiftRuleRepository.update(mbrMbrScoreGiftRule);
    }

    /**
     * 删除积分兑换规则
     */
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public void delMbrScoreGiftRule(Long id, Long merchantId) throws Exception {

        logger.info("删除积分兑换id：" + id);
        Assert.notNull(merchantId, "商户id不能为空");

        MbrScoreGiftRule mbrMbrScoreGiftRule = mbrScoreGiftRuleRepository.fromId(new MbrScoreGiftRuleId(id));
        Assert.isTrue(mbrMbrScoreGiftRule.getMerchantId().getId() == merchantId, "该规则不属于当前商户");
        mbrMbrScoreGiftRule.disable();
        mbrMbrScoreGiftRule.setId(new MbrScoreGiftRuleId(id));
        mbrScoreGiftRuleRepository.update(mbrMbrScoreGiftRule);
    }


    /**
     * 提前结束活动
     * @param id 兑换活动id
     */
    public void finishActivity(Long id,Long merchantId) {
        Objects.requireNonNull(id);
        MbrScoreGiftRule giftRule = mbrScoreGiftRuleRepository.fromId(new MbrScoreGiftRuleId(id));
        if (giftRule == null) {
            throw new BaseException("","积分兑换规则不存在");
        }
        if(!Objects.equals(merchantId,giftRule.getMerchantId().getId())){
            throw new BaseException("","您无权限操作");
        }
        giftRule.finishActivity();
        mbrScoreGiftRuleRepository.update(giftRule);
    }

    /**
     * 修改库存
     * @param id 兑换活动id
     * @param number 数量
     */
    public void updateInventory(Long id, Integer number) {
        Objects.requireNonNull(id);
        MbrScoreGiftRule giftRule = mbrScoreGiftRuleRepository.fromId(new MbrScoreGiftRuleId(id));
        if (giftRule == null) {
            throw new BaseException("","积分兑换规则不存在");
        }
        Date now = new Date();
        if (giftRule.getEndTime().before(now)) {
            throw new BaseException("","兑换活动已结束");
        }
        mbrScoreGiftRuleRepository.updateGoodsInventory(giftRule,number);
    }


}